<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
function employee_add_page() {
    return drupal_get_form('employee_edit_form');
}
function employee_edit_page($id) {
    return drupal_get_form('employee_edit_form', $id);
}

function employee_account_page() {
    global $user;
    return drupal_get_form('employee_edit_form', $user->uid);
}

function employee_edit_form($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $account = user_load( $id);
        $form_state['account'] = $account;
        $record = nonghua_data_load('employee', 'employee_id', $id);
        if (empty($account)&&empty($record)) {
            drupal_set_message(t('员工不存在！'), 'status', FALSE);
            return $form;
        }
        $form_state['update'] = true;
        $form_state['id'] = $id;
    }else{
        $form_state['insert'] = true;
    }
    // 判断用户角色
    if(!nonghua_user_access('employee', 'view', $id, !empty($record) ? $record->author_uid:0,$id) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['employee'] = array(
//        '#type' => 'fieldset',
//        '#title' => '基本信息',
//        '#collapsed' => false,
//        '#collapsible' => true,
    );

    $form['employee']['name'] = array(
        '#type' => 'textfield',
        '#title' => '姓名',
        '#default_value' => !empty($record) ? $record->employee_name : '',
        '#size' => 32,
        '#maxlength' => 10,
        '#required' => TRUE,
    );


    $gender_options = array('男' => '男', '女' => '女');
    $form['employee']['gender'] = array(
        '#type' => 'radios',
        '#title' => '性别',
        '#default_value' => !empty($record) ? $record->gender : '男',
        '#options' => $gender_options,
    );
    $form['employee']['phone'] = array(
        '#type' => 'textfield',
        '#title' => '电话（例如：010 12345678  或者 010-12345678 或者 010--12345678）',
        '#default_value' => !empty($record) ? $record->phone : '',
        '#size' => 32,
        '#maxlength' => 15,
    );

    $form['employee']['cell'] = array(
        '#type' => 'textfield',
        '#title' => '手机',
        '#default_value' => !empty($record) ? $record->cell : '',
        '#size' => 32,
        '#maxlength' => 15,
        '#required' => TRUE,
    );

    $form['employee']['address'] = array(
        '#type' => 'textfield',
        '#title' => '家庭住址',
        '#default_value' => !empty($record) ? $record->address : '',
        '#size' => 32,
        '#maxlength' => 50,
    );
    $form['employee_login'] = array(
//        '#type' => 'fieldset',
//        '#title' => '登录信息',
//        '#collapsed' => true,
//        '#collapsible' => true,
    );
    $form['employee_login']['account'] = array(
        '#type' => 'textfield',
        '#title' => t('用户登录名'),
        '#maxlength' => USERNAME_MAX_LENGTH,
//        '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
        '#required' => TRUE,
        '#disabled' => !empty($account)?true:false,
        '#attributes' => array('class' => array('username')),
        '#default_value' => !empty($account)?$account->name:'',
    );
    $form['employee_work'] = array(
//        '#type' => 'fieldset',
//        '#title' => '工作信息',
//        '#collapsed' => TRUE,
//        '#collapsible' => true,
    );
    _insert_juris_selection_form($form, !empty($record) ? $record->juris_id : '', 'employee_work');

    $form['employee_work'] += _employee_insert_role_department( $form_state,$user->uid, 'employee_work', $level = 3, !empty($record) ? get_user_role($id ): '', !empty($record) ? $record->department_id : '',!empty($record) ? $record->manager_uid : '',"请选择其角色、部门及其经理");

    $form['employee_work']['position'] = array(
        '#type' => 'textfield',
        '#title' => '职位',
        '#default_value' => !empty($record) ? $record->position : '',
        '#size' => 32,
        '#maxlength' => 20,
        '#required' => TRUE,
    );

    $form['employee_work']['company'] = array(
        '#type' => 'textfield',
        '#title' => '单位',
        '#default_value' => !empty($record) ? $record->company : '',
        '#size' => 32,
        '#maxlength' => 50,
        '#required' => TRUE,
    );

//    $form['employee']['role'] = _employee_insert_role($user->uid, !empty($record) ? get_user_role($id ): '');


    $form['employee_other'] = array(
//        '#type' => 'fieldset',
//        '#title' => '备注信息',
//        '#collapsed' => TRUE,
//        '#collapsible' => true,
    );
    $form['employee_other']['comments'] = array(
        '#type' => 'textarea',
        '#title' => '备注',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#cols' => 32,
        '#rows' => 2,
        '#maxlength' => 50
    );


    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '提交',
        '#access' => nonghua_user_access('employee', 'edit', $id, !empty($record) ? $record->author_uid:0, $id)
    );
    return $form;
}

function employee_edit_form_validate($form, &$form_state) {
    pregPN_E_TP($form_state['values']['cell'],$form_state['values']['phone']);
    if(empty($form_state['values']['department'])){
        form_set_error('department', "必须填写 部门");
    }
    if(empty($form_state['values']['role'])){
        form_set_error('role', "必须填写 角色");
    }
    if(empty($form_state['values']['juris'])){
        form_set_error('juris', "必须填写 区域");
    }


    if(isset($form_state['insert']) && $form_state['insert']) {

        if (isset($form_state['values']['account'])&&!empty($form_state['values']['account'])) {
            if ($error = user_validate_name($form_state['values']['account'])) {
                form_set_error('account', $error);
            }
            elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($form_state['values']['account']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
                form_set_error('account', t('The name %name is already taken.', array('%name' => $form_state['values']['account'])));
            }
        }
        if (empty($form_state['values']['account'])) {
            $record = db_select('users', 'u')
                ->condition('u.name', $form_state['values']['cell'])
                ->fields('u')
                ->execute()->fetchAssoc();
            if (!empty($record)) {
                form_set_error('cell', "利用该手机号作为农户登录名，该手机号已存在！");
            }
        }
    }
    
}

function employee_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $transaction = db_transaction();
    try {
        if (empty($id)) {
            // add
            $new_user = array(
                'name' => !empty($form_state['values']['account']) ? $form_state['values']['account'] : $form_state['values']['cell'],
                'pass' =>  '123456',
//                    'mail' => $form_state['values']['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
//                        'init' => $form_state['values']['email'],
                'roles' => array(
                    $form_state['values']['role'] => $form_state['values']['role']
                ),
            );
            $account = user_save('', $new_user);
            if (empty($account->uid)) {
                drupal_set_message(t('添加失败！'), 'status', FALSE);
//                drupal_goto('employee/add');
                return false;
            }

            $nid = db_insert('employee')// Table name no longer needs {}
            ->fields(array(
                'employee_id' => $account->uid,
                'employee_name' => $form_state['values']['name'],
                'gender' => $form_state['values']['gender'],
                'department_id' => $form_state['values']['department'],
                'manager_uid' => $form_state['values']['manager'],
                'position' => $form_state['values']['position'],
                'company' => $form_state['values']['company'],
                'phone' => $form_state['values']['phone'],
                'cell' => $form_state['values']['cell'],
                'address' => $form_state['values']['address'],
                'comments' => $form_state['values']['comments'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('添加成功！'), 'status', FALSE);
            }
//            drupal_goto('employee/list');
        } else {
            //edit
            $new_user = array(
                'name' => !empty($form_state['values']['account']) ? $form_state['values']['account'] : $form_state['values']['cell'],
//                'pass' => !empty($form_state['values']['pass']) ? $form_state['values']['pass'] : '123456',
//                'mail' => $form_state['values']['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
//                    'init' => $form_state['values']['email'],
                'roles' => array(
                    $form_state['values']['role'] => $form_state['values']['role']
                ),
            );
            $account = $form_state['account'];
            user_save($account, $new_user);

            $nid = db_update('employee')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'employee_name' => $form_state['values']['name'],
                'gender' => $form_state['values']['gender'],
                'department_id' => $form_state['values']['department'],
                'manager_uid' => $form_state['values']['manager'],
                'position' => $form_state['values']['position'],
                'company' => $form_state['values']['company'],
                'phone' => $form_state['values']['phone'],
                'cell' => $form_state['values']['cell'],
                'address' => $form_state['values']['address'],
                'comments' => $form_state['values']['comments'],
//                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->condition('employee_id', $id, '=')
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('修改成功！'), 'status', FALSE);
            }
//            drupal_goto('employee/list');
        }
    }catch (Exception $e){
        $transaction->rollback();
        watchdog_exception('user', $e);
        throw $e;
    }
}
